package common.tx;

import common.lang.Transactionary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

import javax.sql.DataSource;
import java.util.function.Function;

/**
 * @Author wangyue
 * @Version 3.0
 * @Date 2025-02-15
 */

public class DataSourceTransactionary implements Transactionary {

    protected PlatformTransactionManager transactionManager;
    protected TransactionTemplate transactionTemplate;

    public DataSourceTransactionary(DataSource dataSource) {
        transactionManager = new DataSourceTransactionManager(dataSource);
        transactionTemplate = new TransactionTemplate(transactionManager);
    }

    public <T> T transact(Function<Object, T> action) {
        return transactionTemplate.execute(txStatus -> {
            try {
                return action.apply(txStatus);
            } catch(Exception x) {
                txStatus.setRollbackOnly(); // 标记回滚
                throw x;
            }
        });
    }

}
